import os
import re
import subprocess
from urllib.parse import quote, unquote

import pyperclip


class GetPushClipper:
    """
    获取手机粘贴板
    推送文本到手机
    """

    def __init__(self):
        self.apk_dir = os.path.join(os.getcwd(), 'platform-tools', r'PhoneTools.apk')
        self.package_name = 'adb.tools.adbtools'

    def _check_and_install_app(self, label):
        """
        检查指定包名的应用是否已安装，如果未安装则安装该应用
        """
        # 检查应用是否已安装
        label("start install app")
        result = self._run_adb_command("adb shell pm list packages")
        if result and self.package_name in result:
            label("app installed")
        else:
            _command = f"adb install {self.apk_dir}"
            install_result = self._run_adb_command(_command)
            if install_result and "Success" in install_result:
                label("app installed")

    def _run_adb_command(self, *commands):
        """
        运行一系列ADB命令，并返回最后一个命令的输出结果
        """
        # 将多个命令连接起来
        full_command = " && ".join(commands)
        try:
            p = subprocess.Popen(full_command, stdout=subprocess.PIPE, shell=True)
            result = p.communicate()[0].decode('utf-8').strip()  # 执行communicate并解码输出
            # self._hide_console()
            return result
        except subprocess.CalledProcessError as e:
            print(f"Error executing command '{full_command}': {e}")
            return None
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

    def _get_current_app(self):
        # 获取当前应用,用于使用服务后返回应用
        re_app_activities = self._run_adb_command('adb shell dumpsys activity activities | findstr "cmp="')
        print("re_app_activities", re_app_activities)
        if re_app_activities:
            current_app_match = re.search('com\.[^\s]+', re_app_activities)
            if current_app_match:
                current_app = current_app_match.group()
                print("re_current_app", current_app)
                return current_app

    def _get_android_clipboard_text(self):
        """
        获取安卓设备的剪贴板中的文本信息
        # 目前的信息是安卓10以上都无法静默启动服务
        """
        return self._run_adb_command(
            "adb shell am start adb.tools.adbtools/.MainActivity",
            "adb shell am broadcast -n adb.tools.adbtools/.ReadReceiver"
        )

    def _parse_android_text(self, android_text):
        """
        解析从安卓设备获取的文本信息
        """
        data_start_index = android_text.find('data="') + len('data="')
        data_end_index = android_text.find('"', data_start_index)
        return android_text[data_start_index:data_end_index]

    def get_android_text(self, label):
        """
        从安卓设备的剪贴板中获取文本信息，并推送到PC的剪贴板中
        """
        self._check_and_install_app(label)
        current_app = self._get_current_app()

        # 启动剪切板服务并获取内容
        android_text = self._get_android_clipboard_text()
        print("Android Text:", android_text)

        if android_text:
            # 解析文本信息
            data = self._parse_android_text(android_text)
            if data:
                # 将数据编码并推送到PC剪贴板,解决乱码问题
                data = quote(data)
                data = data.replace("%20", " ")
                data = unquote(data)
                pyperclip.copy(data)
                self._run_adb_command(f"adb shell am start {current_app}")
                label("get successfully: \n" + data)
                print("current app", current_app)
            else:
                label("android text is None")
        else:
            label("get android text failed")

    def push_PC_text(self, textbox, label):
        """
        PC文本推送到手机粘贴板上
        """
        self._check_and_install_app(label)
        input_text = textbox.toPlainText()
        current_app = self._get_current_app()
        print("input_text", input_text)
        if input_text:
            encoded_text = quote(input_text)
            print("encoded_text ", encoded_text)
            result = self._run_adb_command(
                "adb shell am start adb.tools.adbtools/.MainActivity",
                f'adb shell am broadcast -n adb.tools.adbtools/.WriteReceiver -e text "{encoded_text}"'
            )
            print("result", result)
            self._run_adb_command(f"adb shell am start {current_app}")
            if "SUCCESS" in result:
                label("push successfully: \n" + input_text)
            else:
                label("check phone open settings-UBS install")
        else:
            label("input text")
